package com.xushi.controller;

import com.xushi.bean.ActivityWrapperBean;
import com.xushi.bean.MixedStateBean;
import com.xushi.bean.TimeMap;
import com.xushi.bean.UserTemplateStatus;
import com.xushi.model.Activity;
import com.xushi.model.FreeUsed;
import com.xushi.model.Template;
import com.xushi.model.UserTemplate;
import com.xushi.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/userTemplate")
public class UserTemplateController {
    private final StorageService storageService;
    @Autowired
    private UserTemplateService userTemplateService;
    @Autowired
    private TemplateService templateService;
    @Autowired
    private ActivityService activityService;

    @Autowired
    private TimePriceMapService timePriceMapService;

    @Autowired
    private FreeUsedService freeUsedService;

    public UserTemplateController(StorageService storageService) {
        this.storageService = storageService;
    }

    @PostMapping("/createUserTemplate")
    @ResponseBody
    public HashMap<String, Object> createUserTemplate(@RequestParam int templateId, @RequestParam(required = true) int buyType) {
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        String username = userDetails.getUsername();

        HashMap<String, Object> result = new HashMap<>();
        if (templateId < 0) {
            result.put("code", 2);
            result.put("message", "templateId 不合法");
            return result;
        }

        Template template = templateService.getTemplateById(templateId);
        if (ObjectUtils.isEmpty(template)) {
            result.put("code", 2);
            result.put("message", "模版不存在");
            return result;
        }
        if (!UserTemplateStatus.permitBuy.equals(userTemplateStatus(templateId))) {
            result.put("code", 2);
            result.put("message", "使用getUserTemplateStatus接口查看详情");
            return result;
        }

        try {
            TimeMap timeMap = TimeMap.valueofKey("" + buyType);

            int buyTime = Integer.parseInt(timeMap.getTime());

            if (buyTime == 1) {
                FreeUsed freeUsed = freeUsedService.findFreeUsed("" + templateId, username);
                if (freeUsed != null) {
                    result.put("code", 2);
                    result.put("message", "用户已试用过");
                    return result;
                } else {
                    freeUsedService.addFreeUsed("" + templateId, username);
                }
            }

            Calendar cal = Calendar.getInstance();
            Timestamp currTime = new Timestamp(cal.getTime().getTime());
            cal.add(Calendar.DATE, buyTime);
            Timestamp endTime = new Timestamp(cal.getTime().getTime());
            userTemplateService.createUserTemplate(username, template, currTime, endTime);
        } catch (Exception e) {
            result.put("code", 2);
            result.put("message", e.toString());
            return result;
        }

        result.put("code", 1);
        result.put("message", "创建我的模版成功");
        return result;
    }

    /**
     * 1 表示可以购买 3表示存在有效模版 4表示需要续费
     *
     * @return
     */
    public UserTemplateStatus userTemplateStatus(int templateId) {
        UserTemplateStatus userTemplateStatus = UserTemplateStatus.permitBuy;
        Template template = templateService.getTemplateById(templateId);
        if (ObjectUtils.isEmpty(template)) {
            return UserTemplateStatus.wrongCondition;
        }
        List<UserTemplate> userTemplateList = userTemplateService.getUserTemplateListByTemplate(template);
        if (!CollectionUtils.isEmpty(userTemplateList)) {
            boolean hasValidUserTemplate = false;
            for (UserTemplate userTemplate : userTemplateList) {
                if (UserTemplate.isActive(userTemplate)) {
                    hasValidUserTemplate = true;
                    break;
                }
            }
            if (hasValidUserTemplate) {
                userTemplateStatus = UserTemplateStatus.alreadyHave;
            } else {
                userTemplateStatus = UserTemplateStatus.needPay;
            }
        }

        return userTemplateStatus;
    }

    @GetMapping("/getUserTemplateStatus")
    @ResponseBody
    public UserTemplateStatus getUserTemplateStatus(@RequestParam int templateId) {
        return userTemplateStatus(templateId);
    }

    @PostMapping("/setUserTemplate")
    @ResponseBody

    public HashMap<String, Object> setUserTemplate(@RequestParam("userTemplateId") int userTemplateId,
                                                   @RequestParam("title") String title,
                                                   @RequestParam("playCount") int playCount,
                                                   @RequestParam("description") String description,
                                                   @RequestParam("description2") String description2,
                                                   @RequestParam(value = "qrCode", required = false) MultipartFile qrCode) {
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        String username = userDetails.getUsername();

        HashMap<String, Object> result = new HashMap<>();
        if (playCount < 0) {
            result.put("code", 2);
            result.put("message", "玩家参与次数应当不小于0");
            return result;
        }

        UserTemplate userTemplate = userTemplateService.getUserTemplateById(userTemplateId);
        if (ObjectUtils.isEmpty(userTemplate)) {
            result.put("code", 2);
            result.put("message", "活动不存在");
            return result;
        }

        String weixinQrCodePath = "";
        if (qrCode != null && !qrCode.isEmpty()) {
            storageService.store(qrCode);
            weixinQrCodePath = qrCode.getOriginalFilename();
        }

        try {
            userTemplateService.setUserTemplate(userTemplate.getId(), title, playCount, description, description2, weixinQrCodePath);
        } catch (Exception e) {
            result.put("code", 2);
            result.put("message", e.toString());
            return result;
        }

        result.put("code", 1);
        result.put("message", "设置活动成功");
        return result;
    }

    @GetMapping("/getUserTemplate")
    @ResponseBody
    public HashMap<String, Object> getUserTemplate(@RequestParam("userTemplateId") int userTemplateId) {
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        String username = userDetails.getUsername();
        UserTemplate userTemplate = userTemplateService.getUserTemplateById(userTemplateId);

        HashMap<String, Object> result = new HashMap<>();
        result.put("code", 1);
        result.put("data", userTemplate);
        return result;
    }

    @GetMapping("/getUserTemplateList")
    @ResponseBody
    public HashMap<String, Object> getUserTemplateList() {
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        String username = userDetails.getUsername();
        List<UserTemplate> userTemplateList = userTemplateService.getUserTemplateList(username);
        if (CollectionUtils.isEmpty(userTemplateList)) {
            userTemplateList = new ArrayList<>();
        }
        HashMap<String, Object> result = new HashMap<>();
        result.put("code", 1);
        result.put("data", userTemplateList);
        return result;
    }

    @GetMapping("/getMixedList")
    @ResponseBody
    public HashMap<String, Object> getMixedList() {
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        String username = userDetails.getUsername();

        List<UserTemplate> userTemplateList = userTemplateService.getUserTemplateList(username);

        List<MixedStateBean> mixedStateBeans = new ArrayList<>(userTemplateList.size());
        for (UserTemplate userTemplate : userTemplateList) {
            List<Activity> activeActivities = activityService.getActiveActivitiesByUT(userTemplate);
            ActivityWrapperBean activityWrapperBean = new ActivityWrapperBean(activeActivities);
            MixedStateBean mixedStateBean = new MixedStateBean(userTemplate, activityWrapperBean);
            mixedStateBeans.add(mixedStateBean);
        }
        HashMap<String, Object> result = new HashMap<>();
        result.put("code", 1);
        result.put("data", mixedStateBeans);
        return result;
    }
}
